package com.googlecode.jmicroerp.wicket.components.grid;

import com.googlecode.jmicroerp.model.Entitate;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Alexandru.Codescu
 */
public class ActionPanel<T extends Entitate> extends Panel {
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(ActionPanel.class);
    
    private class LinkView extends ListView<ActionButton> {
        public LinkView(String id, List<ActionButton> parameters) {
            super(id, parameters);
        }

        @Override
        protected void populateItem(ListItem<ActionButton> listItem) {
            final ActionButton actionButton = listItem.getModelObject();
            final T entity = (T) ActionPanel.this.getDefaultModelObject();
            final Long id = entity.getId();
            Link<Void> modificaLink = new Link<Void>("modifica") {
                @Override
                public void onClick() {
                    PageParameters pageParameter = actionButton.getPageParameters();
                    pageParameter.setId(id);

                    try {
                        if (pageParameter.getPageEdit() == null) {
                            actionButton.doAction(id);
                        } else {
                            setResponsePage(pageParameter.getPageEdit());
                        }
                    } catch (InstantiationException iex) {
                        LOGGER.error(iex.getMessage(), iex);
                    } catch (IllegalAccessException iaex) {
                        LOGGER.error(iaex.getMessage(), iaex);
                    } catch (NoSuchMethodException nsmex) {
                        LOGGER.error(nsmex.getMessage(), nsmex);
                    } catch (InvocationTargetException itex) {
                        LOGGER.error(itex.getMessage(), itex);
                    }
                }
            };
            
            modificaLink.add(new Label("labelLink", actionButton.getLabel()));
            modificaLink.setVisible(actionButton.canDisplay(id));

            listItem.add(modificaLink);
        }
    }

    public ActionPanel(String id, IModel<T> model, final List<ActionButton> actionButtons) {
        super(id, model);
        add(new LinkView("actionLinks", actionButtons));
    }
}